// pages/components/countDown/countDown.js
import util from '../../../utils/util2'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 结束时间
    endTime: {            // 属性名
      type: String,     // 类型（必填），目前接受的类型包括：String, Number, Boolean, Object, Array, null（表示任意类型）
      value: null     // 属性初始值（可选），如果未指定则会根据类型选择一个
    },
    //类型,1为正在，2为准备
    type:{
      type:Number,
      value:1
    },
    autionType:{
      type:String,
      value:"kill"
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    day:"00",
    hour:"00",
    minute:"00",
    second:"00",
    ms:'0'
  },
  
  
  /**
   * 组件的方法列表
   */
  methods: {
    timeFormat(param) {//小于10的格式化函数
      return param < 10 ? '0' + param : param;
    },
    formate(time){
      //console.log(time,'1231')
      if(time.length==16){
       //解除后端数据没有过滤掉，newDate为null的bug 
        time = time + ":00"
      }
      let endTime = util.dateFromString(time).getTime();
      let newTime = new Date().getTime();
      // console.log(intDiff)
      var day = 0, hour = 0, minute = 0, second = 0, ms=0;
      //debugger
      if (endTime - newTime > 0) {//转换时间
        let time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        let day = this.timeFormat(parseInt(time / (60 * 60 * 24)));
        let hour = this.timeFormat(parseInt(time % (60 * 60 * 24) / 3600));
        let min = this.timeFormat((parseInt(time % (60 * 60 * 24) % 3600 / 60)));
        let sec = this.timeFormat(parseInt(time % (60 * 60 * 24) % 3600 % 60));
        ms = time*1000 % 1000
        ms = ms < 100 ? "0" + ms : ms
        ms = String(ms).substring(0,1)
        this.setData({
          day,
          hour,
          minute:min,
          second:sec,
          ms
        })
      } else {
        this.setData({
          day:'00',
          hour: '00',
          minute: '00',
          second: '00',
          ms:'0'
        })
        //this.data.timer&&clearInterval(this.data.timer);
      }
    },
  },
  attached: function () {
    //console.log(this.properties.startTime, this.properties.endTime, 'startTime', util, this.properties.type == 1)
    let time = this.properties.endTime 
    // debugger
    let timer = setInterval(() => this.formate(time), 100);
    this.setData({
      timer,
      autionType: this.properties.autionType
    })
  },
  onUnload: function () {
    var that = this
    console.log(this.data.timer, 'setTime')
    clearInterval(that.data.timer);
  },
  detached: function () {
    // 在组件实例被从页面节点树移除时执行
    //debugger
    var that = this
    console.log(this.data.timer,'setTime')
    clearInterval(that.data.timer);
    for (var i = 0; i <= that.data.timer; i++) {
      clearInterval(i);
    }
    this.setData({
      timer:null
    })
    
  },
})
